package com.itheima.stock.service.impl;

import com.itheima.stock.annotation.Limite;
import com.itheima.stock.cache.Cache;
import com.itheima.stock.constant.Constans;
import com.itheima.stock.dto.LoginDTO;
import com.itheima.stock.entity.SysUser;
import com.itheima.stock.enums.CodeEnum;
import com.itheima.stock.exception.Exceptions;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.service.UserService;
import com.itheima.stock.util.IdWorkers;
import com.itheima.stock.util.RedisKeyUtil;
import com.itheima.stock.vo.CaptchaVO;
import com.itheima.stock.vo.LoginVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @文件名: UserServiceImpl
 * @作者: DX
 * @创建日期: 2025/11/7
 * @描述:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private Cache cache;
    @Autowired
    private IdWorkers idWorkers;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    private static final int FOUR = 4;

    @Override
    public LoginVO login(LoginDTO dto) {
        if (ObjectUtils.isEmpty(dto) ||
                ObjectUtils.isEmpty(dto.getUsername()) ||
                ObjectUtils.isEmpty(dto.getPassword()) ||
                ObjectUtils.isEmpty(dto.getCode()) ||
                ObjectUtils.isEmpty(dto.getRkey())
        ) {
            Exceptions.cast(CodeEnum.PRAM_IS_NOT_NULL);
        }

        String captchaInRedis = cache.get(dto.getRkey());

        if (StringUtils.equals(captchaInRedis, dto.getCode())){
            Exceptions.cast(CodeEnum.SYSTEM_VERIFY_CODE_ERROR);
        }

        cache.remove(dto.getRkey());

        SysUser sysUser = sysUserMapper.selectByExample(dto.getUsername(),Constans.USER_STATUS_NU_EXPIRED,Constans.USER_STATUS_NU_EXPIRED);

        if (ObjectUtils.isEmpty(sysUser) || !passwordEncoder.matches(dto.getPassword(),sysUser.getPassword())){
            Exceptions.cast(CodeEnum.SYSTEM_PASSWORD_ERROR);
        }

        return LoginVO.builder()
                .id(sysUser.getId())
                .username(sysUser.getUsername())
                .nickName(sysUser.getNickName())
                .phone(sysUser.getPhone())
                .build();
    }

    @Override
    @Limite
    public CaptchaVO Captcha() {

        String randomAlphabetic = RandomStringUtils.randomAlphabetic(FOUR);

        String redisKey = RedisKeyUtil.generateKey(Constans.CAPTCHA_PREFIX, idWorkers.nextStrId());

        cache.set(redisKey,randomAlphabetic,Constans.CAPTCHA_EXPIRE_TIME);

        return CaptchaVO.builder()
                .code(randomAlphabetic)
                .rkey(redisKey)
                .build();
    }
}